//
//  PhoneBookTool.m
//  ECDH100
//
//  Created by wuping on 16/7/7.
//  Copyright © 2016年 eyescontrol. All rights reserved.
//

#import "PhoneBookTool.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>

//数组是否为空
#define IsArrEmpty(_ref)    (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]]) ||([(_ref) count] == 0))

@implementation PhoneBookTool

+ (void)getPhoneNumberList:(ReceviePhoneBookBlock)block
{
    PhoneBookTool *tool = [[PhoneBookTool alloc] init];
    tool.contactArr = [NSMutableArray array];
    tool.phoneNumberArr = [NSMutableArray array];
    [tool getAddressBookWithPhoneNumber:block];
}

+ (void)getPhoneNumberAndName:(ReceviePhoneBookBlock)block
{
    PhoneBookTool *tool = [[PhoneBookTool alloc] init];
    tool.contactArr = [NSMutableArray array];
    tool.phoneBookArr = [NSMutableArray array];
    [tool getAddressBookWithPhoneNumber:block];
}

+ (BOOL)getAuthorizationStatus
{
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusDenied || ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusRestricted)
    {
        return NO;
    }

    return YES;
}

- (void)getAddressBookWithPhoneNumber:(ReceviePhoneBookBlock)block
{
    if (![PhoneBookTool getAuthorizationStatus])
    {
        return;
    }
    
    CFErrorRef error = nil;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    __block BOOL accessGranted = NO;
    if (&ABAddressBookRequestAccessWithCompletion != NULL)
    {
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            accessGranted = granted;
            dispatch_semaphore_signal(sema);
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        
    }
    else
    { // we're on iOS 5 or older
        accessGranted = YES;
    }
    
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        if (granted)
        {
            //查询所有
            [self filterContentForSearchText:@""];
            if (IsArrEmpty(self.phoneBookArr))
            {
                block(self.phoneNumberArr);
            }
            else
            {
                block(self.phoneBookArr);
            }
        }
    });
    CFRelease(addressBook);
}

- (void)filterContentForSearchText:(NSString *)searchText
{
    CFErrorRef error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    if ([searchText length] == 0)
    {
        //查询所有
        self.contactArr = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
    }
    else
    {
        //条件查询
        CFStringRef cfSearchText = (CFStringRef)CFBridgingRetain(searchText);
        self.contactArr = CFBridgingRelease(ABAddressBookCopyPeopleWithName(addressBook, cfSearchText));
        CFRelease(cfSearchText);
    }
    
    //拼接手机号字符串
    if (self.phoneBookArr == nil)
    {
        NSMutableArray *oldPhoneNumberArr = [NSMutableArray array];
        for (int i = 0; i < self.contactArr.count; i++)
        {
            ABRecordRef thisPerson = CFBridgingRetain([self.contactArr objectAtIndex:i]);
            ABMutableMultiValueRef phoneNumberProperty = ABRecordCopyValue(thisPerson, kABPersonPhoneProperty);
            NSMutableArray *arr = CFBridgingRelease(ABMultiValueCopyArrayOfAllValues(phoneNumberProperty));
            [oldPhoneNumberArr addObjectsFromArray:arr];
            CFRelease(phoneNumberProperty);
            CFRelease(thisPerson);
        }
        
        for (int i = 0; i < oldPhoneNumberArr.count; i++)
        {
            NSMutableString *str = oldPhoneNumberArr[i];
            NSString *newStr = [str stringByReplacingOccurrencesOfString:@"-" withString:@""];
            NSMutableString *mutableStr = [NSMutableString stringWithString:newStr];
            if ([mutableStr rangeOfString:@"+86"].location != NSNotFound)
            {
                newStr = [mutableStr stringByReplacingOccurrencesOfString:@"+86 " withString:@""];
            }
            [self.phoneNumberArr addObject:newStr];
        }
    }
    else    //昵称和手机号
    {
        for (int i = 0; i < self.contactArr.count; i++)
        {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            ABRecordRef thisPerson = CFBridgingRetain([self.contactArr objectAtIndex:i]);
            ABMutableMultiValueRef phoneNumberProperty = ABRecordCopyValue(thisPerson, kABPersonPhoneProperty);
            NSMutableArray *oldPhoneArr = CFBridgingRelease(ABMultiValueCopyArrayOfAllValues(phoneNumberProperty));
            CFStringRef anFullName = ABRecordCopyCompositeName(thisPerson);
            NSString *nameStr = [NSString stringWithFormat:@"%@", anFullName];
            if (nameStr) {
                [dic setObject:nameStr forKey:@"name"];
            }
            NSMutableArray *newPhoneArr = [NSMutableArray array];
            for (int i = 0; i < oldPhoneArr.count; i++)
            {
                NSMutableString *str = oldPhoneArr[i];
                NSString *newStr = [str stringByReplacingOccurrencesOfString:@"-" withString:@""];
                NSMutableString *mutableStr = [NSMutableString stringWithString:newStr];
                if ([mutableStr rangeOfString:@"+86"].location != NSNotFound)
                {
                    newStr = [mutableStr stringByReplacingOccurrencesOfString:@"+86 " withString:@""];
                }
                [newPhoneArr addObject:newStr];
            }
            [dic setObject:newPhoneArr forKey:@"phoneNumber"];
            [self.phoneBookArr addObject:dic];
            
            CFRelease(phoneNumberProperty);
            if (anFullName) {
                CFRelease(anFullName);
            }
            CFRelease(thisPerson);
        }
    }
    CFRelease(addressBook);
}


@end
